package org.dromara.netbar.controller;

import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.constant.NetbarConstants;
import org.dromara.common.core.utils.AssertUtils;
import org.dromara.netbar.domain.bo.NetbarMemberCouponAddBo;
import org.dromara.netbar.domain.vo.NetbarCouponVo;
import org.dromara.netbar.service.INetbarCouponService;
import org.dromara.netbar.service.impl.CouponService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.netbar.domain.vo.NetbarCouponMemberVo;
import org.dromara.netbar.domain.bo.NetbarCouponMemberBo;
import org.dromara.netbar.service.INetbarCouponMemberService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 会员-卡券关联
 *
 * @author Lion Li
 * @date 2025-07-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/netbar/couponMember")
public class NetbarCouponMemberController extends BaseController {

    private final INetbarCouponMemberService netbarCouponMemberService;
    private final INetbarCouponService netbarCouponService;
    private final CouponService couponService;

    /**
     * 查询会员-卡券关联列表
     */
    @SaCheckPermission("netbar:couponMember:list")
    @GetMapping("/list")
    public TableDataInfo<NetbarCouponMemberVo> list(NetbarCouponMemberBo bo, PageQuery pageQuery) {
        return netbarCouponMemberService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出会员-卡券关联列表
     */
    @SaCheckPermission("netbar:couponMember:export")
    @Log(title = "会员-卡券关联", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(NetbarCouponMemberBo bo, HttpServletResponse response) {
        List<NetbarCouponMemberVo> list = netbarCouponMemberService.queryList(bo);
        ExcelUtil.exportExcel(list, "会员-卡券关联", NetbarCouponMemberVo.class, response);
    }

    /**
     * 获取会员-卡券关联详细信息
     *
     * @param couponMemberId 主键
     */
    @SaCheckPermission("netbar:couponMember:query")
    @GetMapping("/{couponMemberId}")
    public R<NetbarCouponMemberVo> getInfo(@NotNull(message = "主键不能为空")
                                           @PathVariable Long couponMemberId) {
        return R.ok(netbarCouponMemberService.queryById(couponMemberId));
    }

    /**
     * 新增会员-卡券关联
     */
    @SaCheckPermission("netbar:couponMember:add")
    @Log(title = "会员-卡券关联", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody NetbarCouponMemberBo bo) {
        return toAjax(netbarCouponMemberService.insertByBo(bo));
    }

    /**
     * 修改会员-卡券关联
     */
    @SaCheckPermission("netbar:couponMember:edit")
    @Log(title = "会员-卡券关联", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody NetbarCouponMemberBo bo) {
        return toAjax(netbarCouponMemberService.updateByBo(bo));
    }

    /**
     * 删除会员-卡券关联
     *
     * @param couponMemberIds 主键串
     */
    @SaCheckPermission("netbar:couponMember:remove")
    @Log(title = "会员-卡券关联", businessType = BusinessType.DELETE)
    @DeleteMapping("/{couponMemberIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] couponMemberIds) {
        return toAjax(netbarCouponMemberService.deleteWithValidByIds(List.of(couponMemberIds), true));
    }

    // 发卷
    @SaCheckPermission("netbar:couponMember:add")
    @Log(title = "会员-卡券下发", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/addMemberCoupon")
    public R<Void> addMemberCoupon(@RequestBody NetbarMemberCouponAddBo bos) {
        AssertUtils.notNull(bos, "请选择卡券");
        AssertUtils.hasSize(bos.getMemberIds(), "请选择会员");
        AssertUtils.hasSize(bos.getCouponMemberBoList(), "请选择卡券");
        List<NetbarCouponVo> netbarCouponVos = netbarCouponService.listCouponNameAndId();
        List<Long> couponIds = netbarCouponVos.stream().map(NetbarCouponVo::getCouponId).toList();
        // 将自动使用的代金券ID拿出来
        List<Long> autoUseDjCouponIdList = netbarCouponVos.stream().filter(c -> NetbarConstants.Coupon.TYPE_1.equals(c.getCouponType())).map(NetbarCouponVo::getCouponId).toList();
        List<NetbarCouponMemberBo> autoUseDjCouponRecordList = new ArrayList<>();
        // 存储
        Map<Long, Long> couponIdMap = new HashMap<>();
        for (NetbarCouponMemberBo couponRecord : bos.getCouponMemberBoList()) {
            AssertUtils.notNull(couponRecord.getCouponId(), "请选择卡券");
            AssertUtils.notNull(couponRecord.getCouponCount(), "请选择卡券数量");
            AssertUtils.isTrue(couponIds.contains(couponRecord.getCouponId()), "卡券不存在");
            if (!couponIdMap.containsKey(couponRecord.getCouponId())) {
                couponIdMap.put(couponRecord.getCouponId(), couponRecord.getCouponCount());
            } else {
                couponIdMap.put(couponRecord.getCouponId(), couponIdMap.get(couponRecord.getCouponId()) + couponRecord.getCouponCount());
            }
        }
        NetbarCouponMemberBo couponRecord;
        Date date = new Date();
        for (Long memberId : bos.getMemberIds()) {
            for (Map.Entry<Long, Long> entry : couponIdMap.entrySet()) {
                for (long l = 0; l < entry.getValue(); l++) {
                    couponRecord = new NetbarCouponMemberBo();
                    couponRecord.setCouponId(entry.getKey());
                    couponRecord.setMemberId(memberId);
                    couponRecord.setCreateTime(date);
                    netbarCouponMemberService.insertByBo(couponRecord);
                    if (autoUseDjCouponIdList.contains(couponRecord.getCouponId())) {
                        autoUseDjCouponRecordList.add(couponRecord);
                    }
                }
            }
        }
        // 自动代金券
//        if(CollectionUtil.isNotEmpty(autoUseDjCouponRecordList)){
//            try {
//                for (NetbarCouponMemberBo netbarCouponMemberBo : autoUseDjCouponRecordList) {
//                    couponService.useCoupon(netbarCouponMemberBo);
//                }
//            }catch (Exception ignored){}
//        }
        return R.ok("操作成功");
    }

    @PostMapping("/deleteCouponMember")
    public R<Void> deleteCouponMember(@RequestBody NetbarCouponMemberBo bo) {
        AssertUtils.notNull(bo, "请选择卡券");
        AssertUtils.hasSize(bo.getMemberIds(), "请选择会员");
        AssertUtils.notNull(bo.getCouponId(), "请选择卡券");
        long couponCount = bo.getCouponCount();
        netbarCouponMemberService.deleteCouponMember(bo);
        return R.ok();
    }
}
